package com.calvin.study.multithread.seckill;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SeckillDemo {
	private static AtomicInteger tGoods = new AtomicInteger(0);

	private static int goods  = 0;
	
	public static void main(String[] args) {
		//test01.seckill();
		//test02.seckill();
		
//		for(int i = 0,len=100;i<=len;i++) {
//			goods = goods + i;
//		}
		
//		for (int i = 1, len = 100; i <= len; i++) {
//			int step = i;
//			new Thread(() -> {
//				tGoods.getAndAdd(step);
//				goods = goods + step;
//			}, String.valueOf(i)).start();
//		}
//		
//		System.out.println(goods);
//		System.out.println(tGoods.get());

	}
	
	//使用AtomicInteger声明num的内存可见性，避免在高并发情况下出现的数据不一致，超卖的问题。
	static class test01 {
		// 采用底层为Cas自旋的方式
		private static AtomicInteger num = new AtomicInteger(2);

		public static void seckill() {
			// 假设10个线程，此时同时访问线程的信号量为5。
			for (int i = 1, len = 50; i <= len; i++) {
				new Thread(() -> {
					try {
						if (num.get() > 0) {
							// 抢到资源
							num.decrementAndGet();
							System.out.println(Thread.currentThread().getName() + "\t秒杀成功");
						} else {
							System.out.println(Thread.currentThread().getName() + "\t秒杀失败");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}).start();
			}
		}
	}
	
	static class test02{
		private static int goods = 2;
		
		private static Lock lock = new ReentrantLock();

		// 显示锁，完成100个人同时秒杀两个商品。
		public static void seckill() {
			for (int i = 1, len = 100; i <= len; i++) {
				new Thread(() -> {
					lock.lock();
					try {
						if (goods <= 0) {
							System.out.println(Thread.currentThread().getName() + "\t活动售罄");
						} else {
							goods --;
							System.out.println(Thread.currentThread().getName() + "\t秒杀成功");
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				}, String.valueOf(i)).start();
			}
		}
	}

}
